package com.flink.socket;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class SocketServer {
    private static final int PORT = 9999;

    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("服务端启动，监听端口: " + PORT);
            System.out.println("等待客户端连接...");

            // 等待客户端连接
            Socket clientSocket = serverSocket.accept();
            System.out.println("客户端已连接: " + clientSocket.getInetAddress());

            // 获取输出流，用于向客户端发送消息
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

            // 获取输入流，用于接收客户端消息
            Scanner in = new Scanner(clientSocket.getInputStream());

            // 启动一个线程接收客户端消息
            Thread receiveThread = new Thread(() -> {
                while (true) {
                    if (in.hasNextLine()) {
                        String clientMessage = in.nextLine();
                        System.out.println("客户端: " + clientMessage);
                    }
                }
            });
            receiveThread.setDaemon(true);
            receiveThread.start();

            // 主线程用于向客户端发送消息
            Scanner consoleScanner = new Scanner(System.in);
            while (true) {
                System.out.print("输入要发送给客户端的消息: ");
                String message = consoleScanner.nextLine();
                out.println(message);
            }
        } catch (IOException e) {
            System.err.println("服务端异常: " + e.getMessage());
        }
    }
}  